package com.kun.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.kun.entity.Book;
import com.kun.service.BookService;
import com.kun.util.UploadCosUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * @description: 图书信息restful API
 * @author: KM
 * 2018年3月27日
 */
@RestController
@Api("获取图书API")
public class BookController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${application.imgSuffix}")
    private String[] imgSuffix;
	
	@Autowired
	private BookService  bookServiceImpl;
	
	@ApiOperation("根据id获取图书")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="path",name="id",dataType="int",required=true,value="图书id"),
    })
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
	@RequestMapping(value = "/api/book/{id}", method = RequestMethod.GET)
    public Book findOneBook(@PathVariable("id") int id) {
        return bookServiceImpl.selectBookById(id);
    }
 
	
	@ApiOperation("分页获取图书")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header",name="begin",dataType="int",required=true,value="请求页数",defaultValue="1"),
        @ApiImplicitParam(paramType="header",name="length",dataType="int",required=true,value="请求长度",defaultValue="10"),
        @ApiImplicitParam(paramType="header",name="jsonString",dataType="String",required=true,value="条件查询:支持type、author、press、name模糊查询，支持shelveTime、borrow排序。接收json格式的参数,如{type:4,borrow:'desc'}",defaultValue="{type:4}"),
    })
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value = "/api/book", method = RequestMethod.GET)
    public Map<String,Object> findAllBook(@RequestHeader int begin,@RequestHeader int length,
    		@RequestHeader String jsonString) {
        return bookServiceImpl.selectAllBook(begin, length, jsonString,false);
    }
 
	@RequiresAuthentication
	@RequiresPermissions("bookInfo:add")
    @RequestMapping(value = "/adminApi/book", method = RequestMethod.POST)
    public void createBook(@RequestBody Book book) {
    	bookServiceImpl.insertReturnPrimaryKey(book);
    }
 
	@RequiresAuthentication
	@RequiresPermissions("bookInfo:update")
    @RequestMapping(value = "/adminApi/book", method = RequestMethod.PUT)
    public void modifyBook(@RequestBody Book book) {
    	bookServiceImpl.updateBook(book);
    }
 
	@RequiresAuthentication
	@RequiresPermissions("bookInfo:delete")
    @RequestMapping(value = "/adminApi/book/{id}", method = RequestMethod.DELETE)
    public void deleteBook(@PathVariable("id") int id) {
    	bookServiceImpl.deleteBook(id);
    }
	
	@RequestMapping(value = "/yeyi/yyUpload", method = RequestMethod.POST)
	@ResponseBody
    public Map<String,Object> uploadCOS(MultipartHttpServletRequest multiReq){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> data = new HashMap<String,Object>();
		try {
			MultipartFile  file = multiReq.getFile("file");
			if (file.isEmpty()) {
				map.put("code", 000400);
				map.put("msg", "上传文件为空");
				return map;
	        }
			// 获取文件名  
	        String fileName = file.getOriginalFilename();  
	        logger.info("yy上传的文件名为：" + fileName);  
	        // 获取文件的后缀名  
	        String suffixName = fileName.substring(fileName.lastIndexOf("."));  
	        logger.info("yy上传的后缀名为：" + suffixName);
	        if(!ArrayUtils.contains(imgSuffix, suffixName)){
	        	//不支持的后缀
	        	map.put("code", 000403);
				map.put("msg", "图片格式必须为'jpg'、'png'、'jpge'、'gif'、'bmp'");
				return map;
	        }
	        String fName = UUID.randomUUID().toString() + suffixName;
			logger.info("yy图片上传： newname：" + fName);
			String cosPath = "/yeyi/";
			String url = UploadCosUtil.picCOS(file, cosPath, fName);
	        map.put("code", 0);
			map.put("msg", "");
			data.put("src", url);
			data.put("title", fName);
			map.put("data", data);
			return map;
		} catch (Exception e) {
			logger.error("yy-failure--"+e.getMessage());
			map.put("code", 1);
			map.put("msg", "上传发生错误");
			return map;
		}
    }

}
